import { defineStore } from 'pinia';
import { reqToken, reqLogin } from '@/api/login';
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '../../utils/token';
import { useTeacherStore } from './teacherStore';
import { useParentStore } from './parentStore';
import { useStudentStore } from './studentStore';
import { showFailToast } from 'vant';
import router from '@/router';

export const useUserStore = defineStore('userId', {
    state: () => ({
        userType: '',
        hasData: false
    }),
    actions: {
        /**
         * 在页面刷新时pinia数据会消失,需要通过判断userType(用户身份)来发送不同的状态库的自动登录请求
         */
        async login(loginForm) {
            try {
                const token = GET_TOKEN();

                if (token == undefined || token == null) {
                    await this.getToken(loginForm);
                }

                let userInfo = { data: {} };

                const userInfoRequest = await this.getUserInfo(userInfo);

                userInfo = userInfoRequest.data;
                // .then(res => (userInfo = res.data))
                // .catch(err => {
                // showFailToast(e.message);
                //     this.logout();
                // });

                switch (this.userType) {
                    case 'teacher':
                        const teacherStore = useTeacherStore();
                        teacherStore.login(userInfo);
                        break;
                    case 'student':
                        const studentStore = useStudentStore();
                        studentStore.login(userInfo);
                        break;
                    case 'parent':
                        const parentStore = useParentStore();
                        parentStore.login(userInfo);
                        break;
                }

                this.hasData = true;
            } catch (e) {
                showFailToast(e.message);
                this.logout();
            }
        },
        async logout({ pathName = 'login', query = {} }) {
            REMOVE_TOKEN();
            router.push({ name: pathName, query: query });
            localStorage.removeItem('userType');
            switch (this.userType) {
                case 'teacher':
                    const teacherStore = useTeacherStore();
                    teacherStore.logout();
                    break;
                case 'student':
                    const studentStore = useStudentStore();
                    studentStore.logout();
                    break;
                case 'parent':
                    const parentStore = useParentStore();
                    parentStore.logout();
                    break;
            }
            this.userType = '';

            this.hasData = false;
        },
        async getUserInfo() {
            // 获取用户信息
            const res = await reqLogin();

            if (res.status == 200) {
                switch (res.data.userType) {
                    case 1:
                        this.userType = 'student';
                        break;
                    case 2:
                        this.userType = 'teacher';
                        break;
                    default:
                        this.userType = 'parent';
                        break;
                }

                return res;
            }
        },
        async getToken(loginForm) {
            // 获取token
            const dataToken = await reqToken({
                userNum: loginForm.account,
                password: loginForm.password,
                verifyCode: loginForm.captcha,
                pageNo: 1
            });
            if (dataToken?.status == 200) {
                SET_TOKEN(dataToken.data);
            } else {
                throw new Error(dataToken.statusText);
            }
        }
    }
});
